import { Drawer, DrawerProps, Form, Input, Select, Spin } from 'antd';
import { memo, useEffect, useImperativeHandle, useRef } from 'react';
import { QueryObserverResult, RefetchOptions, RefetchQueryFilters } from 'react-query';
import { IFormRef, ILawsRef, IPage } from '../../../types';
import { SysUnit, useAddUnit, useGetUnitType, useUpdateUnit } from '../../../service/unit-service';
import { useForm } from 'antd/es/form/Form';
import JdUnitSelect from '../../../components/jd-unit';

const UnitFrom = (
    props: {
        open: boolean;
        onRef: React.MutableRefObject<IFormRef | undefined>;
        refetch: <TPageData>(options?: (RefetchOptions & RefetchQueryFilters<TPageData>) | undefined) => Promise<QueryObserverResult<IPage<SysUnit>, unknown>>
        openFn: React.Dispatch<React.SetStateAction<boolean>>;
        parentId: string | undefined;
        parentName: string | undefined;
        updateUnit?: SysUnit;
    } & DrawerProps,
) => {
    const [form] = useForm();
    const { mutateAsync: addUnitMutation, isLoading: addIsLoading } = useAddUnit();
    const { mutateAsync: updateUnitMutation, isLoading: UIsLoading } = useUpdateUnit();
    /**
            * !获取单位类型HOOK
            */
    const { data: unitTypeDataSource } = useGetUnitType();


    const unitTypes = [{
        value: 1,
        name: "公安",
    }, {
        value: 2,
        name: "社区"
    }]
    useEffect(() => {
        form.setFieldsValue({
            parentName: props.updateUnit?.parentName || props.parentName,
            unitName: props.updateUnit?.unitName,
            unitShortName: props.updateUnit?.unitShortName,
            unitCode: props.updateUnit?.unitCode,
            unitType: props.updateUnit?.unitType,
            orderId: props.updateUnit?.orderId,
        });
        if (props.updateUnit?.jdUnitId) {
            jDunitselectRef.current?.fill(props.updateUnit?.jdUnitId)
        } else {
            jDunitselectRef.current?.fill('')
        }

    }, [props.updateUnit, props.parentName]);

    /**
     * 向外暴露表单的保存和修改
     */
    useImperativeHandle(props.onRef, () => ({
        reset: () => {
            form.resetFields();
        },
        save: async () => {
            const isPass = form.validateFields();
            if (!isPass) {
                return
            }
            const values = form.getFieldsValue();
            await addUnitMutation({ parentId: props.parentId, ...values });
            props.refetch();
            props.openFn(false);
            form.resetFields();
        },
        update: async () => {
            const unitId = props.updateUnit?.unitId;
            if (!unitId) {
                return;
            }
            const values = form.getFieldsValue();
            await updateUnitMutation({ unitId, ...values });
            props.refetch();
            props.openFn(false);
            form.resetFields();
        },
    }));
    const jDunitselectRef = useRef<ILawsRef>();

    const jdSelectHandlerChange = (value: string) => {
        form.setFieldValue("jdUnitId", value)
    }

    return (
        <Drawer title={'单位'} placement="right" width={'35rem'} closable={true} onClose={props.onClose} forceRender={true} open={props.open} footer={props.footer}>
            <Spin spinning={addIsLoading || UIsLoading}>
                <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
                    <Form.Item label={'上级单位'} name={'parentName'}>
                        <Input disabled />
                    </Form.Item>
                    <Form.Item label={'单位简称'} name={'unitShortName'} rules={[{ required: true, message: '单位简称不能为空' }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label={'单位名称'} name={'unitName'} rules={[{ required: true, message: '单位名称不能为空' }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label={'单位编码'} name={'unitCode'}>
                        <Input disabled />
                    </Form.Item>
                    <Form.Item label={'单位类型'} name={'unitType'}>
                        <Select >
                            {
                                unitTypeDataSource?.map((unit) => {
                                    return <Select.Option value={unit.unitTypeId} key={unit.unitTypeId}>
                                        {unit.unitTypeName}
                                    </Select.Option>
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item label={'所属街道'} name={'jdUnitId'} rules={[{ required: true, message: '所属街道不能为空' }]}>
                        <JdUnitSelect handleChange={jdSelectHandlerChange} onRef={jDunitselectRef} />
                    </Form.Item>
                    <Form.Item label={'单位排序'} name={'orderId'}>
                        <Input type={'number'} />
                    </Form.Item>
                </Form>
            </Spin>
        </Drawer>
    );
};


export default memo(UnitFrom);